package com.mkx.configuration;

import com.mkx.aop.RedisLockAspect;
import com.mkx.core.auto.AutoConfigOptimizer;
import com.mkx.core.monitor.SystemLoadMonitor;
import com.mkx.properties.RedisLockProperties;
import com.mkx.template.RedisLockTemplate;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;

@AutoConfiguration
@ConditionalOnClass(RedisTemplate.class)
@EnableConfigurationProperties(RedisLockProperties.class)
@ConditionalOnProperty(prefix = "redis.lock", value = "enabled", havingValue = "true", matchIfMissing = true)
public class RedisLockAutoConfiguration {
    
    @Bean
    @ConditionalOnMissingBean
    public RedisLockTemplate redisLockTemplate(RedisTemplate<String, Object> redisTemplate,
                                               RedisLockProperties properties) {
        return new RedisLockTemplate(redisTemplate, properties);
    }
    
    @Bean
    @ConditionalOnMissingBean
    public RedisLockAspect redisLockAspect(RedisLockTemplate redisLockTemplate) {
        return new RedisLockAspect(redisLockTemplate);
    }
    
    /**
     * 初始化自动配置优化器
     */
    @Bean
    @ConditionalOnProperty(prefix = "redis.lock", value = "auto-config-optimization-enabled", havingValue = "true", matchIfMissing = true)
    public ApplicationRunner autoConfigOptimizerInitializer(RedisTemplate<String, Object> redisTemplate, RedisLockProperties properties) {
        return args -> {
            // 确保系统负载监控器已初始化
            SystemLoadMonitor.getInstance();
            
            // 初始化自动配置优化器
            if (properties.isAutoConfigOptimizationEnabled()) {
                AutoConfigOptimizer optimizer = AutoConfigOptimizer.getInstance();
                optimizer.initialize(properties, redisTemplate);
            }
        };
    }
}